package giermala.dominik.fotka.controller;

import giermala.dominik.fotka.domain.Comment;
import giermala.dominik.fotka.domain.Foto;
import giermala.dominik.fotka.domain.User;
import giermala.dominik.fotka.repository.CommentRepository;
import giermala.dominik.fotka.repository.FotoRepository;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class CommentController {

	private static final Logger logger = LoggerFactory.getLogger(CommentController.class);

	@Autowired
	private CommentRepository commentRepository;
	@Autowired
	private FotoRepository fotoRepository;
	
	@RequestMapping(value = "/add_comment.html", method = RequestMethod.POST)
	public String addComment(@Validated @ModelAttribute Comment comment, BindingResult result, HttpServletRequest request) {

		logger.info("Comment addition");
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				logger.info("Error: " + error.getCode() + " - " + error.getDefaultMessage());
			}
			return "redirect:/compare.html";
		}
		User user = (User)request.getSession().getAttribute("user");
		comment.setFotkaUser(user);
		commentRepository.save(comment);

		Long fotoId = Long.parseLong(request.getParameter("fotoId"));
		Foto foto = fotoRepository.findOne(fotoId);
		
		comment.setDate(new Date());
		comment.setFoto(foto);
		comment.setFotkaUser(user);
		commentRepository.save(comment);
		
		return "redirect:/compare.html";
	}
}
